<?php


namespace app\admin\controller;


use app\admin\service\RequestService;
use app\model\Article;
use app\model\ArticleCate;
use think\wenhainan\Thinkcsv;

class ArticleController extends AController {

    protected function initialize(){

        $this->model = new Article();

        parent::initialize();
    }



    public function index(RequestService $curdService): \think\response\Json
    {
        try {
            $list = $curdService->index($this->model, ['cate'], []);
            $list = $list->each(function ($v) {
                $v->cateTitle = getRelValue($v->cate, 'title');
            });
            return jsonSuccess([
                'total' => $list->total(),
                'data' => $list->items(),
            ]);

        }catch (\Exception $e){
            return jsonError($e->getMessage());
        }

    }


    public function add(RequestService $curdService){
        return $curdService->add($this->model);
    }

    public function edit(RequestService $curdService){
        if (request()->isPost()){
            return $curdService->edit($this->model);
        }else{
            $id = request()->param('id');
            $info = $this->model::where('id', $id)->find();
            if($info){
                return jsonSuccess([
                    'info' => $info
                 ]);
            }else{
                return jsonError("无此记录");
            }
        }

    }


    public function del(RequestService $curdService){
        return $curdService->del($this->model);
    }


    public function export(){// 不限制脚本执行时间以确保导出完成


        $date = request()->param('date','');

        if (!$date){
            return jsonError('请选择日期');
        }

        $header = [
            'ac.name' => '栏目',
            'a.title' => '标题',
            'a.content' => '内容',
            'a.hits' => '点击',
            'a.create_time' => '添加时间',
            'a.update_time' => '更新时间',
        ];

        $data = $this->model->alias('a')
            ->field(array_keys($header))
            ->order('create_time desc')
            ->join('article_cate ac', 'a.cate_id = ac.id')
            ->whereTime('a.create_time', 'between', $date)
            ->select()->toArray();

        //浏览器访问渲染下载
        $csv = new Thinkcsv(rand(100000000,9999999999).'.csv', array_values($header), $data);
        $csv->export();

    }


    protected function formatList($list){
        $list = $list->each(function ($v) {
            $v->cateTitle = getRelValue($v->cate, 'title');
        });
        return $list;
    }


}
